// src/utils/request.js
import axios from 'axios';
import router from '@/router';
import { ElMessage } from 'element-plus';

// 创建 axios 实例
const service = axios.create({
  baseURL: 'http://192.168.1.3:8000',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  }
});

// 不需要验证token的白名单路径
const whiteList = ['/login', '/register']

// 是否正在刷新token
let isRefreshing = false;
// 重试队列
let requests = [];

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    // 优先使用 access token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 处理文件下载等特殊响应
    if (response.config.responseType === 'blob') {
      return response.data;
    }
    
    const res = response.data;
    if (!res) {
      ElMessage.error('接口返回数据异常');
      return Promise.reject(new Error('接口返回数据异常'));
    }
    
    return res;
  },
  async (error) => {
    const originalRequest = error.config;
    
    // 如果是401错误（token过期）且不是刷新token的请求
    if (error.response?.status === 401 && !originalRequest._retry) {
      if (isRefreshing) {
        // 如果正在刷新token，将请求加入队列
        return new Promise(resolve => {
          requests.push((token) => {
            originalRequest.headers['Authorization'] = `Bearer ${token}`;
            resolve(service(originalRequest));
          });
        });
      }

      originalRequest._retry = true;
      isRefreshing = true;

      try {
        const refresh_token = localStorage.getItem('refresh_token');
        if (!refresh_token) {
          throw new Error('No refresh token');
        }

        // 调用刷新token的接口
        const response = await service.post('/token/refresh?refresh_token='+refresh_token);

        const { token, refresh_token: new_refresh_token } = response.data;
        
        // 更新本地存储的token
        localStorage.setItem('token', token);
        localStorage.setItem('refresh_token', new_refresh_token);

        // 更新当前请求的token
        originalRequest.headers['Authorization'] = `Bearer ${token}`;

        // 执行队列中的请求
        requests.forEach(cb => cb(token));
        requests = [];

        return service(originalRequest);
      } catch (err) {
        // 刷新token失败，清除token并跳转到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('refresh_token');
        router.push('/login');
        return Promise.reject(error);
      } finally {
        isRefreshing = false;
      }
    }

    // 处理其他错误
    let errorInfo = {
      code: error.response?.status || 500,
      message: '服务器错误'
    };
    if (error.response) {      
      switch (error.response.status) {
        case 400:
          ElMessage.error(error.response.data.detail || '服务器错误')
          break;
        case 403:
          ElMessage.error('拒绝访问');
          break;
        case 404:
          ElMessage.error('请求的资源不存在');
          break;
        case 500:
          ElMessage.error('服务器内部错误');
          break;
        default:
          ElMessage.error(error.response.data?.message || '未知错误');
          break;
        }
    } else if (error.request) {
      ElMessage.error('无法连接到服务器');
    } else {
      ElMessage.error(error.message || '请求配置错误');
    }

    return Promise.reject(errorInfo);
  }
);

// 封装请求方法
const request = {
  // GET 请求改为使用 POST 方法，以支持 body 传参
  get(url, data = {}) {
    return service({
      url,
      method: 'get', 
      params: data,
      headers: {
        'Content-Type': 'application/json',
        'X-HTTP-Method-Override': 'GET' // 添加标识，让后端知道这是 GET 请求
      }
    });
  },
  
  // POST 请求
  post(url, data = {}) {
    return service({
      url,
      method: 'post',
      data
    });
  },
  
  // PUT 请求
  put(url, data = {}) {
    return service({
      url,
      method: 'post', 
      data,
      headers: {
        'X-HTTP-Method-Override': 'PUT' 
      }
    });
  },
  
  // DELETE 请求
  delete(url, data = {}) {
    return service({
      url,
      method: 'post', 
      data,
      headers: {
        'X-HTTP-Method-Override': 'DELETE' 
      }
    });
  },

  // 文件上传
  upload(url, file, onUploadProgress) {
    const formData = new FormData();
    formData.append('file', file);
    
    return service({
      url,
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress
    });
  },

  // 文件下载
  download(url, data = {}, fileName = '') {
    return service({
      url,
      method: 'post',
      data,
      responseType: 'blob'
    }).then(response => {
      const blob = new Blob([response]);
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = fileName || '下载文件';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(downloadUrl);
    });
  }
};

export default request;